/**
 * 角色与权限管理钩子集合
 * 
 * 本模块提供了角色和权限管理相关的数据操作钩子，基于React Query实现。
 * 主要职责：
 * 1. 获取角色列表和详情数据
 * 2. 提供角色添加、更新和删除功能
 * 3. 获取和更新角色权限
 * 4. 权限树数据处理和维护
 * 
 * 这些钩子将复杂的角色与权限管理逻辑封装，提供统一的接口，
 * 简化了组件实现，增强了代码复用性和可维护性。
 * 
 * @module hooks/useRoleManagement
 */
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { message } from 'antd';
import { Role, Right } from '../types';
import { 
  getRoleList, 
  getRoleById, 
  addRole, 
  updateRole, 
  updateRoleRights, 
  deleteRole
} from '../api/roleApi';
import { 
  getRights, 
  getRightsWithChildren, 
  updateRightState, 
  updateChildRightState, 
  deleteRight, 
  deleteChildRight 
} from '../api/rightsApi';

// API响应数据处理函数
function processApiResponse<T>(response: unknown): T {
  if (!response) return {} as T;
  
  // 处理可能的不同响应格式
  if (typeof response === 'object' && response !== null) {
    // 如果响应对象有data属性
    if ('data' in response && response.data !== undefined) {
      const data = (response as { data: unknown }).data;
      // 可能有嵌套的data结构
      if (typeof data === 'object' && data !== null && 'data' in data) {
        return (data as { data: T }).data;
      }
      return data as T;
    }
  }
  
  // 如果无法处理，返回原始响应
  return response as T;
}

/**
 * 角色列表钩子
 * @returns 角色列表数据和相关状态
 */
export const useRoleList = () => {
  // 获取角色列表
  const { 
    data: roles, 
    isLoading, 
    error, 
    refetch 
  } = useQuery({
    queryKey: ['roles'],
    queryFn: async () => {
      const res = await getRoleList();
      
      // 处理响应数据格式
      return processApiResponse<Role[]>(res);
    }
  });
  
  return {
    roles: roles || [],
    isLoading,
    error,
    refetch
  };
};

/**
 * 获取角色详情
 * @param id 角色ID
 * @returns 角色详情
 */
export const useRoleDetail = (id?: number) => {
  return useQuery({
    queryKey: ['role', id],
    queryFn: async () => {
      if (!id) return null;
      const res = await getRoleById(id);
      return processApiResponse<Role>(res);
    },
    enabled: !!id
  });
};

/**
 * 添加角色钩子
 * @returns 添加角色函数和状态
 */
export const useAddRole = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (roleData: Omit<Role, 'id'>) => addRole(roleData),
    onSuccess: () => {
      message.success('角色添加成功');
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    },
    onError: (error) => {
      message.error(`角色添加失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  });
};

/**
 * 更新角色钩子
 * @returns 更新角色函数和状态
 */
export const useUpdateRole = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, data }: { id: number, data: Partial<Role> }) => 
      updateRole(id, data),
    onSuccess: () => {
      message.success('角色更新成功');
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    },
    onError: (error) => {
      message.error(`角色更新失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  });
};

/**
 * 更新角色权限钩子
 * @returns 更新角色权限函数和状态
 */
export const useUpdateRoleRights = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, rights }: { id: number, rights: string[] }) => 
      updateRoleRights(id, rights),
    onSuccess: () => {
      message.success('权限分配成功');
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    },
    onError: (error) => {
      message.error(`权限分配失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  });
};

/**
 * 删除角色钩子
 * @returns 删除角色函数和状态
 */
export const useDeleteRole = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (id: number) => deleteRole(id),
    onSuccess: () => {
      message.success('角色删除成功');
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    },
    onError: (error) => {
      message.error(`角色删除失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  });
};

/**
 * 获取权限列表钩子
 * @returns 权限列表
 */
export const useRightsList = () => {
  return useQuery({
    queryKey: ['rights'],
    queryFn: async () => {
      const res = await getRights();
      console.log('权限列表API返回:', res);
      
      // 处理响应数据格式
      const rightData = processApiResponse<Right[]>(res);
      
      // 确保每个权限有seqId字段
      return rightData.map(right => {
        const processed = { ...right };
        
        // 如果没有seqId，使用其他字段
        if (!processed.seqId) {
          if (typeof processed.id === 'number') {
            processed.seqId = processed.id;
          } else {
            console.warn('权限数据缺少seqId:', processed);
            processed.seqId = Math.floor(Math.random() * 1000000);
          }
        }
        
        return processed;
      });
    }
  });
};

// 权限树节点类型
interface RightTreeNode {
  id: number;
  seqId?: number;
  title: string;
  key: string;
  pagepermisson?: number;
  grade: number;
  children?: RightTreeNode[];
}

/**
 * 获取带有子权限的权限树形结构
 * @returns 权限树形数据
 */
export const useRightsTree = () => {
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  
  const { 
    data: rightsTree, 
    isLoading, 
    error 
  } = useQuery({
    queryKey: ['rightsTree'],
    queryFn: async () => {
      const res = await getRightsWithChildren();
      console.log('权限树API返回:', res);
      
      // 处理响应数据格式
      const rightData = processApiResponse<RightTreeNode[]>(res);
      
      // 处理空的children数组和确保节点有key属性
      const processedData = rightData.map((item: RightTreeNode) => {
        // 确保每个权限都有seqId
        if (!item.seqId) {
          if (typeof item.id === 'number') {
            item.seqId = item.id;
          } else {
            console.warn('权限数据缺少seqId:', item);
            item.seqId = Math.floor(Math.random() * 1000000);
          }
        }
        
        // 处理空的children数组
        if (item.children && Array.isArray(item.children) && item.children.length === 0) {
          item.children = undefined;
        }
        
        // 添加key属性以便Tree组件使用
        if (!item.key && item.id) {
          item.key = item.id.toString();
        }
        
        // 处理子权限
        if (item.children && Array.isArray(item.children)) {
          item.children = item.children.map((child: RightTreeNode) => {
            // 确保子权限也有seqId
            if (!child.seqId) {
              if (typeof child.id === 'number') {
                child.seqId = child.id;
              } else {
                console.warn('子权限数据缺少seqId:', child);
                child.seqId = Math.floor(Math.random() * 1000000);
              }
            }
            
            // 使用seqId作为key
            if (!child.key && child.seqId) {
              child.key = child.seqId.toString();
            } else if (!child.key && child.id) {
              child.key = child.id.toString();
            }
            
            return child;
          });
        }
        
        return item;
      });
      
      return processedData;
    }
  });
  
  // 控制Tree组件的展开和选择
  const onExpand = (expandedKeysValue: string[]) => {
    setExpandedKeys(expandedKeysValue);
  };
  
  const onCheck = (checkedKeysValue: string[] | { checked: string[], halfChecked: string[] }) => {
    if (Array.isArray(checkedKeysValue)) {
      setCheckedKeys(checkedKeysValue);
    } else {
      setCheckedKeys(checkedKeysValue.checked);
    }
  };
  
  const onSelect = (selectedKeysValue: string[]) => {
    setSelectedKeys(selectedKeysValue);
  };
  
  return {
    rightsTree: rightsTree || [],
    isLoading,
    error,
    expandedKeys,
    checkedKeys,
    selectedKeys,
    onExpand,
    onCheck,
    onSelect,
    setCheckedKeys
  };
};

/**
 * 更新权限状态钩子
 * @returns 更新权限状态函数和状态
 */
export const useUpdateRightState = () => {
  const queryClient = useQueryClient();
  
  const updateRightStateMutation = useMutation({
    mutationFn: ({ id, pagepermisson, isChild = false }: { id: number, pagepermisson: number, isChild?: boolean }) => 
      isChild ? updateChildRightState(id, pagepermisson) : updateRightState(id, pagepermisson),
    onSuccess: () => {
      message.success('权限状态更新成功');
      queryClient.invalidateQueries({ queryKey: ['rightsTree'] });
      queryClient.invalidateQueries({ queryKey: ['rights'] });
    },
    onError: (error) => {
      message.error(`权限状态更新失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  });
  
  return {
    updateRightState: (id: number, pagepermisson: number, isChild: boolean = false) => {
      updateRightStateMutation.mutate({ id, pagepermisson, isChild });
    },
    isLoading: updateRightStateMutation.isPending
  };
};

/**
 * 删除权限钩子
 * @returns 删除权限函数和状态
 */
export const useDeleteRight = () => {
  const queryClient = useQueryClient();
  
  const deleteRightMutation = useMutation({
    mutationFn: ({ id, isChild = false }: { id: number, isChild?: boolean }) => 
      isChild ? deleteChildRight(id) : deleteRight(id),
    onSuccess: () => {
      message.success('权限删除成功');
      queryClient.invalidateQueries({ queryKey: ['rightsTree'] });
      queryClient.invalidateQueries({ queryKey: ['rights'] });
    },
    onError: (error) => {
      message.error(`权限删除失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  });
  
  return {
    deleteRight: (id: number, isChild: boolean = false) => {
      deleteRightMutation.mutate({ id, isChild });
    },
    isLoading: deleteRightMutation.isPending
  };
};

export default {
  useRoleList,
  useRoleDetail,
  useAddRole,
  useUpdateRole,
  useUpdateRoleRights,
  useDeleteRole,
  useRightsList,
  useRightsTree,
  useUpdateRightState,
  useDeleteRight
}; 